package com.ek.kademlia.handlers;

import java.io.Serializable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ek.common.AbstractMessageHandler;
import com.ek.common.Context;
import com.ek.kademlia.protocol.FindValueRequest;
import com.ek.kademlia.protocol.impl.DefaultFindValueResponse;
import com.ek.service.mina.ComunicationService;

public class FindValueRequestHandler extends AbstractMessageHandler<FindValueRequest> {
    private static final transient Logger log = LoggerFactory.getLogger(FindValueRequestHandler.class);

    public FindValueRequestHandler(Context context) {
        super(context);
    }

    @Override
    protected void doExecute(FindValueRequest message, SocketAddress address) {
        log.debug("received FIND_VALUE rpc request from bucket with this socketAddress:" + address + " and this FindValueRequest:" + message);
        String key = message.getKey();
        Serializable value = getContext().getData().get(key);
        DefaultFindValueResponse response = new DefaultFindValueResponse();
        response.setMessageID(message.getMessageID());
        response.setNodeID(getContext().getNodeID());
        response.setValue(value);
        InetSocketAddress socketAddress = (InetSocketAddress) address;
        log.debug("sending FIND_VALUE rpc response to bucket with this socketAddress:" + socketAddress + " and this FindValueResponse:" + response);
        getContext().getComunicationService().sendResponse(response, new InetSocketAddress(socketAddress.getAddress(), ComunicationService.PORT));
    }

    public static String getMessageClass() {
        return FindValueRequest.class.getCanonicalName();
    }
}
